<?php
/*
 * @Author: your name
 * @Date: 2020-05-11 10:28:42
 * @LastEditTime: 2020-05-27 22:33:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /v3/application/adminapiv3/service/permissionsManage/Permissions.php
 */
namespace app\adminapiv3\service\permissionsManage ;

use app\adminapiv3\service\Base;
use think\Db;

class PermissionsService extends Base
{

    /**
     * @name 所有权限菜单
     * @return array|\PDOStatement|string|\think\Collection
     * @author wx
     * @date 2020/7/9 8:43
     */
    function allPermissionsList()
    {
        $fields = 'id, text, parent_id, is_parent';
        $permissionsList = db('server_permissions')
            ->field($fields)
            ->where('hidden', 0)
            ->order('sort asc')->select();

        return $permissionsList;
    }


    /**
     * @name: 权限列表
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-05-11 10:30:36
     */
    function groupPermissionsList ($userGroupId)
    {
//        $userGroupId = $this->getUserInfo('user_group_id');

        $fields = 'is_get, is_do, is_excute, is_delete';

        //所有权限
        $permissionsList = $this->allPermissionsList();

        //当前组权限
        $groupList = db('ServerUserGroupPermissionsRelation')
            ->field($fields)->where('user_group_id', $userGroupId)
            ->column($fields, 'permissions_id');

        $data = array();
        foreach ($permissionsList as $k => $permission){

            $permission['is_get'] = isset($groupList[$permission['id']]) ?  $groupList[$permission['id']]['is_get'] : 0;
            $permission['is_do'] = isset($groupList[$permission['id']]) ?  $groupList[$permission['id']]['is_do'] : 0;
            $permission['is_excute'] = isset($groupList[$permission['id']]) ?  $groupList[$permission['id']]['is_excute'] : 0;
            $permission['is_delete'] = isset($groupList[$permission['id']]) ?  $groupList[$permission['id']]['is_delete'] : 0;

            $data[$k] = $permission;
        }


        $this->permissionsList($data, $return, 0,0);

        return $return;
    }


    /**
     * @name: 菜单列表
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-05-27 21:45:52
     */
    public function menuList ($userId)
    {
        //如果是软件就不显示系统配置 1软件 2硬件
//      $type = db('system_config')->value('type');
        $field = 'sp.id, sp.parent_id, is_parent, text, path, type, name, is_get, is_do, is_delete, is_excute';

        $menuObj = db('server_user_permissions_relation')->alias('supr')
            ->join('server_permissions sp', 'supr.permissions_id = sp.id')
            ->where('user_id', $userId)
            ->where('hidden', 0);

//        if($type == 1){
//            $menuObj->where('text', '<>', '系统配置');
//        }

        $menu = $menuObj->order('sort','asc')
                ->field($field)
                ->select();

        $menu_list = array();

        $this->createMenu($menu, $menu_list,0,0);

        return $menu_list;
    }

    /**
     * @name 生成菜单
     * @param $data
     * @param $list_array
     * @param $array_id
     * @param $parent_id
     * @author wx
     * @date 2020/6/24 9:33
     */
    function createMenu($data, &$list_array, $array_id, $parent_id)
    {

        foreach ($data as $key => $value) {
            if ($value['parent_id'] == $parent_id) {

                if($value['is_get'] == 0){//无查看权限,就隐藏该菜单
                    continue;
                }

                $array_tmp  = array(
                    "text" => $value['text'],
                    "path" => $value['path'],
                    "type" => $value['type'],
                    "name" => $value['name'],
                    "read" => $value['is_get'],
                    "write" => $value['is_do'],
                    "delete" => $value['is_delete'],
                    "other" => $value['is_excute'],
                    //"children"=> array()
                );

                $list_array[$array_id] = $array_tmp;

                if($value['is_parent'] == 1)
                {
                    $this->createmenu($data, $list_array[$array_id]['children'], 0,$value['id']);
                }

                $array_id++;
            }
        }

    }


    /**
     * @name 所有权限列表
     * @param $data
     * @param $list_array
     * @param $array_id
     * @param $parent_id
     * @author wx
     * @date 2020/7/8 21:43
     */
    function permissionsList($data, &$list_array, $array_id, $parent_id)
    {

        $optionArr = [
            'is_get' => 'read',
            'is_do' => 'write',
            'is_delete' => 'delete',
            'is_excute' => 'other',
        ];

        foreach ($data as $key => $value) {
            if ($value['parent_id'] == $parent_id) {

                $array_tmp['id'] = $value['id'];
                $array_tmp['text'] = $value['text'];

                foreach ($optionArr as $php => $html){
                    switch ($value[$php])
                    {
                        case 1:
                            $array_tmp[$html] = true;
                        break;
                        case 0:
                            $array_tmp[$html] = false;
                        break;
                        default:
                            $array_tmp[$html] = 'disabled';
                    }
                }

//                $array_tmp  = array(
//                    "id" => $value['id'],
//                    "text" => $value['text'],
//                    "read" => $value['is_get'] == 1 ? true : false,
//                    "write" => $value['is_do']== 1 ? true : false,
//                    "delete" => $value['is_delete']== 1 ? true : false,
//                    "other" => $value['is_excute']== 1 ? true : false,
//                );

                $list_array[$array_id] = $array_tmp;

                if($value['is_parent'] == 1)
                {
                    $this->permissionsList($data, $list_array[$array_id]['children'], 0, $value['id']);
                }

                $array_id++;
            }
        }


    }

    /**
     * @name: 修改用户组权限
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-05-26 16:25:42
     */
    function modifyUserGroupPermissions ($userGroupId, $operationals)
    {
        //查询出当前等级
        $userGroupInfo = db('server_user_group')->field('upper_id, level')->where('id', $userGroupId)->find();

        $user = $this->getUserInfo();
        if($userGroupInfo['level'] == $user['user_group_level']){
            returnErrJson($this->CODE_FAIL, '无法对此组进行操作');
        }


        if(empty($userGroupInfo)){
            returnErrJson($this->CODE_FAIL, '不存在当前用户组');
        }

        $upperPermissionsList = db('ServerUserGroupPermissionsRelation')
            ->where('user_group_id', $userGroupInfo['upper_id'])
            ->column('is_get, is_do, is_excute, is_delete', 'permissions_id');


        foreach ((array) $operationals as $permission_id => $operational)
        {
            if (isset($upperPermissionsList[$permission_id])) {
                $tmp['is_get'] = $upperPermissionsList[$permission_id]['is_get'] ? $operational['read'] : 0;
                $tmp['is_do'] = $upperPermissionsList[$permission_id]['is_do'] ? $operational['write'] : 0;
                $tmp['is_excute'] = $upperPermissionsList[$permission_id]['is_excute'] ? $operational['other'] : 0;
                $tmp['is_delete'] = $upperPermissionsList[$permission_id]['is_delete'] ? $operational['delete'] : 0;
            }else{
                $tmp['is_get'] = 0;
                $tmp['is_do'] = 0;
                $tmp['is_excute'] = 0;
                $tmp['is_delete'] = 0;
            }

            $tmp['permissions_id'] = $permission_id;
            $tmp['user_group_id'] = $userGroupId;


            $where['user_group_id'] = $userGroupId;
            $where['permissions_id'] = $permission_id;
            $count = db('ServerUserGroupPermissionsRelation')->where($where)->count();

            if($count == 0){//添加
                db('ServerUserGroupPermissionsRelation')->insert($tmp);
            }else{//修改
                db('ServerUserGroupPermissionsRelation')->where($where)->update($tmp);
            }

        }
    }

    /**
     * @name 用户权限列表
     * @author wx
     * @date 2020/12/22 17:48
     */
    public function userPermissionsList($user_id)
    {
        //1. 根据user_id查询用户组id
        $userGroupId = Db::name('server_user')->where('id', $user_id)->value('user_group_id');
        if(!$userGroupId){
            returnErrJson($this->CODE_FAIL, '用户组不存在');
        }

        //所有权限
        $permissionsList = $this->allPermissionsList();

        //用户组权限
        $fields = 'is_get, is_do, is_excute, is_delete';
        $groupPermissionList = db('ServerUserGroupPermissionsRelation')
            ->field($fields)->where('user_group_id', $userGroupId)
            ->column($fields, 'permissions_id');


        //用户权限
        $userPermissionList = db('server_user_permissions_relation')
            ->field($fields)
            ->where('user_id', $user_id)
            ->column($fields, 'permissions_id');

        $option = ['is_get', 'is_do', 'is_delete', 'is_excute'];
        foreach ($permissionsList as $k => $v){
            if (isset($groupPermissionList[$v['id']])) {
                foreach ($groupPermissionList as $permissionId => $value){

                    if($v['id'] == $permissionId){

                        foreach ($option as $item){
                            if($value[$item] == 1){
                                $tmp[$item] = isset($userPermissionList[$permissionId]) ?  $userPermissionList[$permissionId][$item] : 0;
                            }else{
                                $tmp[$item] =  -1;
                            }
                        }

                    }

                }
            }else{

                foreach ($option as $item){
                    $tmp[$item] =  -1;
                }

            }
            $tmp['id'] = $v['id'];
            $tmp['text'] = $v['text'];
            $tmp['parent_id'] = $v['parent_id'];
            $tmp['is_parent'] = $v['is_parent'];


            $data[$k] = $tmp;


        }


        $this->permissionsList($data, $return, 0,0);

        return $return;
    }

    /**
     * @name: 修改用户组权限
     * @Param:
     * @Description:
     * @Author: foo
     * @Date: 2020-05-26 16:25:42
     */
    function modifyUserPermissions ($userId, $operationals)
    {
        if($userId == 1){
            returnErrJson($this->CODE_FAIL, '当前用户权限不能修改');
        }

        //当前登录用户id
        $user = $this->getUserInfo();


        if ($userId == $user['user_id']) {
            returnErrJson($this->CODE_FAIL, '不能修改自己的权限');
        }

        //查询用户组
        $userGroupId = Db::name('server_user')->where('id', $userId)->value('user_group_id');

        if(!$userGroupId){
            returnErrJson($this->CODE_FAIL, '当前用户不存在');
        }

        //查询出当前等级
        $userGroupInfo = db('server_user_group')->field('upper_id, level')->where('id', $userGroupId)->find();

        if($userGroupInfo['level'] == $user['user_group_level']){
            returnErrJson($this->CODE_FAIL, '无法对此组进行操作');
        }


        if(empty($userGroupInfo)){
            returnErrJson($this->CODE_FAIL, '不存在当前用户组');
        }

        //查询当前操作用户的用户组权限
        $upperPermissionsList = db('ServerUserGroupPermissionsRelation')
            ->where('user_group_id', $userGroupId)
            ->column('is_get, is_do, is_excute, is_delete', 'permissions_id');


        foreach ((array) $operationals as $permission_id => $operational)
        {
            if (isset($upperPermissionsList[$permission_id])) {
                $tmp['is_get'] = $upperPermissionsList[$permission_id]['is_get'] ? $operational['read'] : 0;
                $tmp['is_do'] = $upperPermissionsList[$permission_id]['is_do'] ? $operational['write'] : 0;
                $tmp['is_excute'] = $upperPermissionsList[$permission_id]['is_excute'] ? $operational['other'] : 0;
                $tmp['is_delete'] = $upperPermissionsList[$permission_id]['is_delete'] ? $operational['delete'] : 0;
            }else{
                $tmp['is_get'] = 0;
                $tmp['is_do'] = 0;
                $tmp['is_excute'] = 0;
                $tmp['is_delete'] = 0;
            }

            $tmp['permissions_id'] = $permission_id;
            $tmp['user_id'] = $userId;


            $where['user_id'] = $userId;
            $where['permissions_id'] = $permission_id;
            $count = db('server_user_permissions_relation')->where($where)->count();

            if($count == 0){//添加
                db('server_user_permissions_relation')->insert($tmp);
            }else{//修改
                db('server_user_permissions_relation')->where($where)->update($tmp);
            }

        }
    }

}